import axios,{AxiosInstance,AxiosRequestConfig} from 'axios';
import Modal from '../../components/pc/modal';
import {PlainObject} from '../../../types';

let {
	VUE_APP_REQUEST_DIRECT:requestDirect,
	VUE_APP_PROXY_HOST,
	VUE_APP_PROXY_USERNAME,
	VUE_APP_PROXY_PASSWORK,
	VUE_APP_PROXY_LOGINNAME,
	VUE_APP_REQUEST_TIMEOUT,
	proxyHost,
	proxyUserName,
	proxyPassword,
	proxyLoginName,
	requestTimeout,
}=process.env;
proxyHost||=VUE_APP_PROXY_HOST;
proxyUserName||=VUE_APP_PROXY_USERNAME;
proxyPassword||=VUE_APP_PROXY_PASSWORK;
proxyLoginName||=VUE_APP_PROXY_LOGINNAME;
requestTimeout||=VUE_APP_REQUEST_TIMEOUT;
const requestTimeoutNum=parseInt(requestTimeout||'6000');
let myAxios:Promise<AxiosInstance>;
if(requestDirect==='true'){
	myAxios=Promise.resolve(axios.create({
		method:'post',
		baseURL:'/lexmis/rest/',
		timeout:requestTimeoutNum
	}));
}else{
	if(proxyHost){
		const tokenUrl=`${proxyHost}/seeyon/rest/token/${proxyUserName}/${proxyPassword}?loginName=${encodeURIComponent(proxyLoginName||'')}`;
		myAxios=axios.get<any>(tokenUrl,{
			timeout:requestTimeoutNum
		}).then(function(response){
			return axios.create({
				method:'post',
				baseURL:'/seeyon/rest/',
				headers:{
					token:response.data.id
				},
				timeout:requestTimeoutNum
			});
		});
	}else{
		myAxios=Promise.resolve(axios.create({
			method:'post',
			baseURL:'/seeyon/rest/',
			timeout:requestTimeoutNum
		}));
	}
}
/**
 * 请求服务器
 * @param url 请求路径
 * @param data 请求参数
 * @param config 请求配置
 * @return Promise,接收的值是服务器返回的数据
 */
function service(url:string,data:PlainObject={},config?:AxiosRequestConfig):Promise<any>{
	if(config?.method==='get'){
		config.params=data;
	}else if(data.params==null){
		data.params={};
	}
	const req=myAxios.then(function(axios){
		return axios.request(
			Object.assign({
				url,
				data,
			},config)
		);
	});
	return req.then(function(response){
		return response.data;
	}).catch(function(e){
		if(e.response){
			if(e.response.data.message){
				Modal.error({
					title:'错误',
					content:e.response.data.message,
				});
			}else{
				Modal.error({
					title:'HTTP请求失败',
					content:'服务器错误！',
				});
			}
			console.log('HTTP请求失败(服务器错误)',e.response,url,data);
		}else if(e.request){
			Modal.error({
				title:'HTTP请求失败',
				content:'请求已发送，未响应！',
			});
			console.log('HTTP请求失败(未响应)',url,data);
		}else{
			Modal.error({
				title:'HTTP请求失败',
				content:'请求异常！',
			});
			console.log('HTTP请求失败(请求异常)',url,data);
		}
		throw e;
	});
}
/**
 * 根据图片文件id,获取图片的链接
 * @param fileId 图片文件id
 * @return 图片链接
 */
function getImg(fileId:string){
	return (proxyHost||location.origin)+'/seeyon/fileUpload.do?method=showRTE&type=image&fileId='+fileId;
}
export {
	//请求服务器
	service,
	//根据文件id获取图片的链接
	getImg,
};
